﻿/*
 * Created by SharpDevelop.
 * User: Guy Fomi
 * Date: 2/6/2011
 * Time: 2:14 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections;
using System.Collections.Generic;
using HtmlAgilityPack;
using System.Web.Script.Serialization;

namespace TomatoSynchronizer.Store
{
	/// <summary>
	/// Description of WeightClassStore.
	/// </summary>
	public class WeightClassStore
	{
		private Site _site;
		private HtmlWeb _client;
		
		public WeightClassStore(Site site,HtmlWeb client)
		{
			_site = site;
			_client = client;
		}
		
		private IDictionary GetWeightClass(string WeightClassId)
		{
			List<IDictionary> entries = new List<IDictionary>();
			string url = _site.Url + "/admin/json.php?action=load_weight_classes&module=weight_classes&weight_class_id=" + WeightClassId;
			
			HtmlDocument doc = _client.Load(url);
			HtmlNode node = doc.DocumentNode.SelectSingleNode("/");
			
			List<IDictionary> rules = new List<IDictionary>();
			JavaScriptSerializer serialiser = new JavaScriptSerializer();
			IDictionary json = serialiser.Deserialize<IDictionary>(node.InnerText);
			foreach(string key in json.Keys)
			{
				if(key == "data")
				{					
					IDictionary WeightClass = (IDictionary)json[key];		
					
					foreach(string cle in WeightClass.Keys)
					{
						switch(cle)
						{
							case "rules":								
								object[] recs = (object[])WeightClass[cle];
								for(int i = 0;i < recs.Length;i++)
								{
									IDictionary rule = (IDictionary)recs[i];
									rules.Add(rule);
								}								
								break;							
						}
					}
					
					WeightClass["rules"] = rules;					
					
					entries.Add(WeightClass);
				}
			}			
			
			return entries[0];
		}
		
		public List<IDictionary> GetWeightClasses()
		{
			List<IDictionary> WeightClasses = new List<IDictionary>();
			
			HtmlDocument doc = _client.Load(_site.Url + "/admin/json.php?action=list_weight_classes&module=weight_classes");
			HtmlNode node = doc.DocumentNode.SelectSingleNode("/");
			
			JavaScriptSerializer serialiser = new JavaScriptSerializer();
			IDictionary json = serialiser.Deserialize<IDictionary>(node.InnerText);
			foreach(string key in json.Keys)
			{
				if(key == "records")
				{
					object[] recs = (object[])json[key];
					for(int i = 0;i < recs.Length;i++)
					{
						IDictionary record = (IDictionary)recs[i];	
						IDictionary WeightClass = GetWeightClass(record["weight_class_id"].ToString());
						WeightClasses.Add(WeightClass);												
					}									
				}
			}			
			
			return WeightClasses;
		}		
	}
}
